<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-bounce.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ipvb.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false,"b2t":true,"scrollpercent":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="redis集群搭建在开始redis集群搭建之前，我们先简单回顾一下redis单机版的搭建过程 下载redis压缩包，然后解压压缩文件；进入到解压缩后的redis文件目录（此时可以看到Makefile文件），编译redis源文件；把编译好的redis源文件安装到&#x2F;usr&#x2F;local&#x2F;redis目录下，如果&#x2F;local目录下没有redis目录，会自动新建redis目录；进入&#x2F;usr&#x2F;local&#x2F;red">
<meta property="og:type" content="article">
<meta property="og:title" content="redis集群搭建">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/index.html">
<meta property="og:site_name" content="Chenyumeng的博客">
<meta property="og:description" content="redis集群搭建在开始redis集群搭建之前，我们先简单回顾一下redis单机版的搭建过程 下载redis压缩包，然后解压压缩文件；进入到解压缩后的redis文件目录（此时可以看到Makefile文件），编译redis源文件；把编译好的redis源文件安装到&#x2F;usr&#x2F;local&#x2F;redis目录下，如果&#x2F;local目录下没有redis目录，会自动新建redis目录；进入&#x2F;usr&#x2F;local&#x2F;red">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001140534311.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001141620400.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/2018100114273634.png">
<meta property="og:image" content="d:%5C%E7%AC%94%E8%AE%B0%E8%B5%84%E6%96%99%5CRedis%5C%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA%5Cimages%5C20181001142902121.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001142941621.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001150344737.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001150609235.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001151921344.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001152259456.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001155254288.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001155619828.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001160619425.png">
<meta property="og:image" content="d:%5C%E7%AC%94%E8%AE%B0%E8%B5%84%E6%96%99%5CRedis%5C%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA%5Cimages%5C20181001160630117.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001161520287.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001161757158.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/20181001162628508.png">
<meta property="article:published_time" content="2020-03-16T09:51:53.000Z">
<meta property="article:modified_time" content="2020-07-04T11:49:51.484Z">
<meta property="article:author" content="Chenyumeng">
<meta property="article:tag" content="笔记">
<meta property="article:tag" content="CentOS">
<meta property="article:tag" content="linux">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="集群">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ipvb.gitee.io/blog/assets/img/20181001140534311.png">

<link rel="canonical" href="https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>redis集群搭建 | Chenyumeng的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <link rel="stylesheet" href="/dist/css/share.min.css">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chenyumeng的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">热爱自己，热爱生活</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">29</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">1</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">32</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="search-pop-overlay">
  <div class="popup search-popup">
      <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

  </div>
</div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chen-yumeng" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/touxiang.JPG">
      <meta itemprop="name" content="Chenyumeng">
      <meta itemprop="description" content="用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chenyumeng的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          redis集群搭建
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-16 17:51:53" itemprop="dateCreated datePublished" datetime="2020-03-16T17:51:53+08:00">2020-03-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-04 19:49:51" itemprop="dateModified" datetime="2020-07-04T19:49:51+08:00">2020-07-04</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">学习</span></a>
                </span>
            </span>

          
            <span id="/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/" class="post-meta-item leancloud_visitors" data-flag-title="redis集群搭建" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.8k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="redis集群搭建"><a href="#redis集群搭建" class="headerlink" title="redis集群搭建"></a>redis集群搭建</h1><p>在开始redis集群搭建之前，我们先简单回顾一下redis单机版的搭建过程</p>
<p>下载redis压缩包，然后解压压缩文件；<br>进入到解压缩后的redis文件目录（此时可以看到Makefile文件），编译redis源文件；<br>把编译好的redis源文件安装到/usr/local/redis目录下，如果/local目录下没有redis目录，会自动新建redis目录；<br>进入/usr/local/redis/bin目录，直接./redis-server启动redis（此时为前端启动redis）；<br>将redis启动方式改为后端启动，具体做法：把解压缩的redis文件下的redis.conf文件复制到/usr/local/redis/bin目录下，然后修改该redis.conf文件-&gt;daemonize：no 改为daemonize：yse；<br>在/bin目录下通过./redis-server redis.conf启动redis（此时为后台启动）。<br>综上redis单机版安装启动完成。<br>具体详细带图步骤请参考 -&gt; redis入门<br>请原谅我的啰嗦，ok，接着咱们回到本次话题—-redis集群搭建！</p>
<a id="more"></a>

<h2 id="一、Redis-Cluster（Redis集群）简介"><a href="#一、Redis-Cluster（Redis集群）简介" class="headerlink" title="一、Redis Cluster（Redis集群）简介"></a>一、Redis Cluster（Redis集群）简介</h2><ul>
<li>redis是一个开源的key value存储系统，受到了广大互联网公司的青睐。redis3.0版本之前只支持单例模式，在3.0版本及以后才支持集群，我这里用的是redis3.0.0版本；</li>
<li>redis集群采用P2P模式，是完全去中心化的，不存在中心节点或者代理节点；</li>
<li>redis集群是没有统一的入口的，客户端（client）连接集群的时候连接集群中的任意节点（node）即可，集群内部的节点是相互通信的（PING-PONG机制），每个节点都是一个redis实例；</li>
<li>为了实现集群的高可用，即判断节点是否健康（能否正常使用），redis-cluster有这么一个投票容错机制：如果集群中超过半数的节点投票认为某个节点挂了，那么这个节点就挂了（fail）。这是判断节点是否挂了的方法；</li>
<li>那么如何判断集群是否挂了呢? -&gt; 如果集群中任意一个节点挂了，而且该节点没有从节点（备份节点），那么这个集群就挂了。这是判断集群是否挂了的方法；</li>
<li>那么为什么任意一个节点挂了（没有从节点）这个集群就挂了呢？ -&gt; 因为集群内置了16384个slot（哈希槽），并且把所有的物理节点映射到了这16384[0-16383]个slot上，或者说把这些slot均等的分配给了各个节点。当需要在Redis集群存放一个数据（key-value）时，redis会先对这个key进行crc16算法，然后得到一个结果。再把这个结果对16384进行求余，这个余数会对应[0-16383]其中一个槽，进而决定key-value存储到哪个节点中。所以一旦某个节点挂了，该节点对应的slot就无法使用，那么就会导致集群无法正常工作。</li>
<li>综上所述，每个Redis集群理论上最多可以有16384个节点。</li>
</ul>
<h2 id="二、集群搭建需要的环境"><a href="#二、集群搭建需要的环境" class="headerlink" title="二、集群搭建需要的环境"></a>二、集群搭建需要的环境</h2><p>2.1 Redis集群至少需要3个节点，因为投票容错机制要求超过半数节点认为某个节点挂了该节点才是挂了，所以2个节点无法构成集群。</p>
<p>2.2 要保证集群的高可用，需要每个节点都有从节点，也就是备份节点，所以Redis集群至少需要6台服务器。因为我没有那么多服务器，也启动不了那么多虚拟机，所在这里搭建的是伪分布式集群，即一台服务器虚拟运行6个redis实例，修改端口号为（7001-7006），当然实际生产环境的Redis集群搭建和这里是一样的。<br>2.3 安装ruby</p>
<h2 id="三、集群搭建具体步骤如下（注意要关闭防火墙）"><a href="#三、集群搭建具体步骤如下（注意要关闭防火墙）" class="headerlink" title="三、集群搭建具体步骤如下（注意要关闭防火墙）"></a>三、集群搭建具体步骤如下（注意要关闭防火墙）</h2><p>3.1 在usr/local目录下新建redis-cluster目录，用于存放集群节点</p>
<p><img src="/blog/assets/img/20181001140534311.png" alt=""></p>
<p>3.2 把redis目录下的bin目录下的所有文件复制到/usr/local/redis-cluster/redis01目录下，不用担心这里没有redis01目录，会自动创建的。操作命令如下（注意当前所在路径）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cp -r redis&#x2F;bin&#x2F; redis-cluster&#x2F;redis01</span><br></pre></td></tr></table></figure>

<p><img src="/blog/assets/img/20181001141620400.png" alt=""></p>
<p>3.3 删除redis01目录下的快照文件dump.rdb，并且修改该目录下的redis.cnf文件，具体修改两处地方：一是端口号修改为7001，二是开启集群创建模式，打开注释即可。分别如下图所示：<br>删除dump.rdb文件</p>
<p><img src="/blog/assets/img/2018100114273634.png" alt=""></p>
<p>修改端口号为7001,默认是6379</p>
<p><img src="D:%5C%E7%AC%94%E8%AE%B0%E8%B5%84%E6%96%99%5CRedis%5C%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA%5Cimages%5C20181001142902121.png" alt=""></p>
<p>将cluster-enabled yes 的注释打开</p>
<p><img src="/blog/assets/img/20181001142941621.png" alt=""></p>
<p>3.4 将redis-cluster/redis01文件复制5份到redis-cluster目录下（redis02-redis06），创建6个redis实例，模拟Redis集群的6个节点。然后将其余5个文件下的redis.conf里面的端口号分别修改为7002-7006。分别如下图所示：<br>创建redis02-06目录</p>
<p><img src="/blog/assets/img/20181001150344737.png" alt=""></p>
<p>分别修改redis.conf文件端口号为7002-7006</p>
<p><img src="/blog/assets/img/20181001150609235.png" alt=""></p>
<p>3.5 接着启动所有redis节点，由于一个一个启动太麻烦了，所以在这里创建一个批量启动redis节点的脚本文件，命令为start-all.sh，文件内容如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">cd redis01</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br><span class="line">cd redis02</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br><span class="line">cd redis03</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br><span class="line">cd redis04</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br><span class="line">cd redis05</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br><span class="line">cd redis06</span><br><span class="line">.&#x2F;redis-server redis.conf</span><br><span class="line">cd ..</span><br></pre></td></tr></table></figure>

<p>3.6 创建好启动脚本文件之后，需要修改该脚本的权限，使之能够执行，指令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">chmod +x start-all.sh</span><br></pre></td></tr></table></figure>

<p><img src="/blog/assets/img/20181001151921344.png" alt=""></p>
<p>3.7 执行start-all.sh脚本，启动6个redis节点</p>
<p><img src="/blog/assets/img/20181001152259456.png" alt=""></p>
<p>3.8 ok，至此6个redis节点启动成功，接下来正式开启搭建集群，以上都是准备条件。大家不要觉得图片多看起来冗长所以觉得麻烦，其实以上步骤也就一句话的事情：创建6个redis实例（6个节点）并启动。<br>要搭建集群的话，需要使用一个工具（脚本文件），这个工具在redis解压文件的源代码里。因为这个工具是一个ruby脚本文件，所以这个工具的运行需要ruby的运行环境，就相当于java语言的运行需要在jvm上。所以需要安装ruby，指令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum install ruby</span><br></pre></td></tr></table></figure>

<p>然后需要把ruby相关的包安装到服务器，我这里用的是redis-3.0.0.gem，大家需要注意的是：redis的版本和ruby包的版本最好保持一致。<br>将Ruby包安装到服务器：需要先下载再安装，如图</p>
<p><img src="/blog/assets/img/20181001155254288.png" alt=""></p>
<p>然后需要把ruby相关的包安装到服务器，我这里用的是redis-3.0.0.gem，大家需要注意的是：redis的版本和ruby包的版本最好保持一致。<br>将Ruby包安装到服务器：需要先下载再安装，如图</p>
<p>安装命令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gem install redis-3.0.0.gem</span><br></pre></td></tr></table></figure>

<p><img src="/blog/assets/img/20181001155619828.png" alt=""></p>
<p>3.9 上一步中已经把ruby工具所需要的运行环境和ruby包安装好了，接下来需要把这个ruby脚本工具复制到usr/local/redis-cluster目录下。那么这个ruby脚本工具在哪里呢？之前提到过，在redis解压文件的源代码里，即redis/src目录下的redis-trib.rb文件。</p>
<p><img src="/blog/assets/img/20181001160619425.png" alt=""></p>
<p><img src="D:%5C%E7%AC%94%E8%AE%B0%E8%B5%84%E6%96%99%5CRedis%5C%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA%5Cimages%5C20181001160630117.png" alt=""></p>
<p>3.10 将该ruby工具（redis-trib.rb）复制到redis-cluster目录下，指令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cp redis-trib.rb &#x2F;usr&#x2F;local&#x2F;redis-cluster</span><br></pre></td></tr></table></figure>

<p>然后使用该脚本文件搭建集群，指令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.&#x2F;redis-trib.rb create --replicas 1 47.106.219.251:7001 47.106.219.251:7002 47.106.219.251:7003 47.106.219.251:7004 47.106.219.251:7005 47.106.219.251:7006</span><br></pre></td></tr></table></figure>

<p>注意：此处大家应该根据自己的服务器ip输入对应的ip地址！</p>
<p><img src="/blog/assets/img/20181001161520287.png" alt=""></p>
<p>中途有个地方需要手动输入yes即可</p>
<p><img src="/blog/assets/img/20181001161757158.png" alt=""></p>
<p>至此，Redi集群搭建成功！大家注意最后一段文字，显示了每个节点所分配的slots（哈希槽），这里总共6个节点，其中3个是从节点，所以3个主节点分别映射了0-5460、5461-10922、10933-16383solts。</p>
<p>3.11 最后连接集群节点，连接任意一个即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redis01&#x2F;redis-cli -p 7001 -c</span><br></pre></td></tr></table></figure>

<p>注意：一定要加上-c，不然节点之间是无法自动跳转的！如下图可以看到，存储的数据（key-value）是均匀分配到不同的节点的：</p>
<p><img src="/blog/assets/img/20181001162628508.png" alt=""></p>
<p>四、结语<br>呼<del>长舒一口气…终于搭建好了Redis集群。<br>整个过程其实挺简单，本篇主要正对入门级别的小伙伴，插入了很多图片，所以显得冗长，希望大家多多理解，如果不当之处，还望及时指正</del></p>
<p>最后，加上两条redis集群基本命令：<br>1.查看当前集群信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cluster info</span><br></pre></td></tr></table></figure>

<p>2.查看集群里有多少个节点</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cluster nodes</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    
    <div>    
      
        <ul class="post-copyright">
          <li class="post-copyright-link">
          <strong>本文作者：</strong>
          <a href="/" title="欢迎访问 Chenyumeng 的个人博客">Chenyumeng</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文标题：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/" title="redis集群搭建">redis集群搭建</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文链接：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/" title="redis集群搭建">https://ipvb.gitee.io/blog/2020/03/16/redis%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/</a>
          </li>

          <li class="post-copyright-date">
            <strong>发布时间： </strong>2020年3月16日 - 17时03分
          </li>  

          <li class="post-copyright-license">
            <strong>版权声明： </strong>
            本文由 Chenyumeng 原创。
          </li>
        </ul>
      
    </div>
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\ZooKeeper\" rel="bookmark">ZooKeeper单机与集群安装笔记</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\centOs7_Redis\" rel="bookmark">centOs7下安装Redis记录</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\16\linux JDK安装\" rel="bookmark">linux JDK安装</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\16\linux MySQL安装\" rel="bookmark">linux MySQL安装</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\Redis_translate\" rel="bookmark">Redis所有命令+集群（翻译转载）</a></div>
    </li>
  </ul>

        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/images/wechatpay.png" alt="Chenyumeng 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/images/alipay.png" alt="Chenyumeng 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------　　　　本文结束　<i class="fa fa-heart"></i>　感谢您的阅读　　　　-------------</div>
    
</div>
        
      </div>

      <footer class="post-footer">
          
          <div class="post-tags">
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/03/16/linux%20MySQL%E5%AE%89%E8%A3%85/" rel="prev" title="linux MySQL安装">
      <i class="fa fa-chevron-left"></i> linux MySQL安装
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/03/24/LeetCode%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%981%EF%BC%88%E6%8C%89%E6%91%A9%E5%B8%88%EF%BC%89/" rel="next" title="LeetCode每日一题1（按摩师）">
      LeetCode每日一题1（按摩师） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

    <!-- 引入share.js -->
    
      <div data-weibo-title="分享到微博" data-qq-title="分享到QQ" data-douban-title="分享到豆瓣" class="social-share" class="share-component" data-disabled="twitter,facebook" data-description="Share.js - 一键分享到微博，QQ空间，腾讯微博，人人，豆瓣">分享到：</div>
    
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80OTExNy8yNTYxMg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#redis集群搭建"><span class="nav-number">1.</span> <span class="nav-text">redis集群搭建</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、Redis-Cluster（Redis集群）简介"><span class="nav-number">1.1.</span> <span class="nav-text">一、Redis Cluster（Redis集群）简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、集群搭建需要的环境"><span class="nav-number">1.2.</span> <span class="nav-text">二、集群搭建需要的环境</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、集群搭建具体步骤如下（注意要关闭防火墙）"><span class="nav-number">1.3.</span> <span class="nav-text">三、集群搭建具体步骤如下（注意要关闭防火墙）</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Chenyumeng"
      src="/blog/images/touxiang.JPG">
  <p class="site-author-name" itemprop="name">Chenyumeng</p>
  <div class="site-description" itemprop="description">用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">29</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/chen-yumeng" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;chen-yumeng" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/3123221441" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;3123221441" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://github.com/" title="https:&#x2F;&#x2F;github.com&#x2F;" rel="noopener" target="_blank">Github</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chenyumeng</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">390k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">5:55</span>
</div>

        






  <script>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : '',
            'X-LC-Key'    : '',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>


      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

  <script src="/dist/js/social-share.min.js"></script>
</body>
</html>
